<?php

namespace App\Blocks;

use App\Models\WechatConfig;
use App\Models\WechatUser;
use DB;

class WechatBlock
{

    //获取微信配置信息
    public function we_config($data)
    {
        $WeConfig = new WechatConfig();
        $sql = DB::table($WeConfig->getTable())
            ->select('id as key', 'name', 'base_url', 'we_type', 'app_id', 'secret', 'token', 'aes_key', 'update_time');
        $list = $this->like_select($sql, $data)->get();
        return $list;
    }

    private function like_select($sql, $data)
    {
        foreach ($data as $key => $value) {
            if ($value != '') {
                if (is_numeric($value)) {
                    $sql->where($key, $value);
                } else {
                    $sql->where( $key, 'like', '%' . $value . '%');
                }

            }
        }

        return $sql;
    }


    //修改微信配置信息
    public function we_update($id, $data)
    {
        $WeConfig = new WechatConfig();

        $res = DB::table($WeConfig->getTable())->where('id', $id)->update($data);
        return $res;
    }

    //删除微信配置信息
    public function weconfig_delete($id)
    {
        $Weconfig = new WechatConfig();
        $sql = DB::table($Weconfig->getTable());
        if (is_array($id)){
                $sql->whereIn('id',$id);
        }else{
            $sql->where('id',$id);
        }
        return $sql->delete();
    }

    public function wechat_add($data)
    {
        $WeConfig = new WechatConfig();
        $res = DB::table($WeConfig->getTable())->insert($data);
        return $res;
    }

    //获取公众号微信用户
    public function we_user($subscribe, $page, $pagesize)
    {
        $WeUser = new WechatUser();
        if ($page == '') {
            $page = 1;
        }
        if ($pagesize == '') {
            $pagesize = 5;
        }
        $sql = DB::table($WeUser->getTable())
            ->select('wechat_id', 'nickname', 'city', 'province', 'country', 'sex', 'headimgurl', 'subscribe', 'subscribe_time')
            ->whereNull('deleted_at');
        $total = $sql->get()->count();
        if ($subscribe == 'all' || !isset($subscribe)) {
            $WeUserdata = $sql;
        } elseif ($subscribe == 0) {
            $WeUserdata = $sql->where('subscribe', 0);
        } elseif ($subscribe == 1) {
            $WeUserdata = $sql->where('subscribe', 1);
        }
        $total = $WeUserdata->get()->count();
        $list = $WeUserdata->offset(($page - 1) * $pagesize)->limit($pagesize)->get();
        $res = array(
            'list' => $list,
            'pagination' => array(
                'total' => $total,
                'pagesize' => $pagesize,
                'current' => $page
            )
        );
        return $res;
    }
}